Component({
  options: {
    styleIsolation: "shared",
  },
  behaviors: [],
  properties: {
    haveRes: Boolean,
  },
  data: {
    keyword: "",
    searched: false,
    history: [],
  },
  lifetimes: {
    created() {
      wx.getStorage({
        key: "history",
        success: result => {
          this.setData({ history: result.data });
        },
      });
      this.setData({
        bottomSafe: wx.getStorageSync('bottomSafe') + 'px',
      })
    },
  },
  methods: {
    /**
     * 搜索关键词为空清空数据
     */
    onChange() {
      if (this.data.keyword.trim() === "") {
        this.setData({
          searched: false,
        });
        this.triggerEvent("clearResult");
      }
    },
    /**
     * 查找搜索结果
     * @param {*} keyword
     * @returns
     */
    onSearch() {
      const { keyword, history } = this.data;
      if (keyword.trim() === "") {
        wx.showToast({
          title: "关键词不能为空",
          icon: "none",
        });
        return;
      }
      this.setData({ searched: true });
      if (history.indexOf(keyword) !== -1) {
        let index = history.indexOf(keyword);
        history.splice(index, 1);
      }
      history.unshift(keyword);
      this.setData({ history });
      wx.setStorage({
        data: history,
        key: "history",
        flag: true,
      });
      this.getList();
    },
    /**
     * 取消搜索
     */
    onCancel() {
      this.setData({ keyword: "", searched: false });
      this.triggerEvent("clearResult");
    },
    /**
     * 获取列表
     */
    getList() {
      this.triggerEvent("getResult", this.data.keyword);
    },
    /**
     * 点击历史记录标签进行搜索
     * @param {*} e
     */
    searchHistory(e) {
      let keyword = e.currentTarget.dataset.tag;
      this.setData({ keyword });
      this.onSearch();
    },
    /**
     * 清除历史记录
     */
    onClear() {
      wx.setStorage({
        data: [],
        key: "history",
        success: res => {
          this.setData({ history: [] });
        },
      });
    },
  },
});
